import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Input, Table, Select, Popconfirm, notification } from 'antd';
import usePageAccess from '@/components/usePageAccess';
import { Access, history } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryEmployeeListParams, Employee } from './services';
import { EmployeeStatus, queryEmployeeList, delEmployee, passRest } from './services'
import { enum2options } from '@/utils/enum2options';
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import { jump2target } from '@/utils/common';

const EmployeePage: React.FC = () => {
  const access = usePageAccess()
  const [searchForm] = Form.useForm<QueryEmployeeListParams>()
  const [searchParams, setSearchParams] = useState<QueryEmployeeListParams>({
    pageNum: 1, pageSize: 10,
  })
  const employeeList = useRequest(() => queryEmployeeList(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: delEmployeeAsync } = useRequest(delEmployee, {manual: true})
  const { runAsync: passRestAsync } = useRequest(passRest, {manual: true, onSuccess: () => {
    notification.success({
      message: '密码重置成功'
    })
  }})

  const openEditPage = (title: string, type: string, employeeId?: number) => {
    jump2target(`/system/managerList/edit?type=${type}&id=${employeeId || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/system/managerList/edit_title', title)
  }

  const onFinish = (formValues: QueryEmployeeListParams) => {
    setSearchParams({
      ...searchParams,
      ...formValues,
      pageNum: 1,
    })
  }

  const columns: ColumnsType<Employee> = [
    {
      title: '员工姓名',
      dataIndex: 'username',
    },
    {
      title: '登录账号',
      dataIndex: 'telephone',
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      render: createTime => dayjs(createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: status => status && EmployeeStatus[status]
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 200,
      fixed: 'right',
      render: (id: number, record) => {
        const isAdmin = record.telephone === 'admin'
        return <Space>
          <Access accessible={!isAdmin}>
            <a onClick={() => openEditPage('编辑员工', 'edit', id)}>编辑</a>
          </Access>
          <Access accessible={!isAdmin && record.status === EmployeeStatus.启用}>
            <Popconfirm
              title={`确定禁用员工: ${record.username} 吗?`}
              onConfirm={() => delEmployeeAsync({id: record.id, status: EmployeeStatus.禁用}).then(employeeList.refresh)}
              okText="禁用"
              cancelText="取消"
            >
              <a>禁用</a>
            </Popconfirm>
          </Access>
          <Access accessible={!isAdmin && record.status === EmployeeStatus.禁用}>
            <Popconfirm
              title={`确定启用员工: ${record.username} 吗?`}
              onConfirm={() => delEmployeeAsync({id: record.id, status: EmployeeStatus.启用}).then(employeeList.refresh)}
              okText="启用"
              cancelText="取消"
            >
              <a>启用</a>
            </Popconfirm>
          </Access>
          <Access accessible={!isAdmin}>
            <Popconfirm
              title={`确定删除员工: ${record.username} 吗?`}
              onConfirm={() => delEmployeeAsync({id: record.id, status: 3}).then(employeeList.refresh)}
              okText="删除"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
          </Access>
          <Popconfirm
            title={`确定重置员工: ${record.username} 的密码吗?重置后密码为“123456”`}
            onConfirm={() => passRestAsync({id: record.id})}
            okText="重置"
            cancelText="取消"
          >
            <a>重置密码</a>
          </Popconfirm>
        </Space>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      employeeList.refresh()
    }
    window.addEventListener('refreshEmployeeList', refresh)
    return () => {
      window.removeEventListener('refreshEmployeeList', refresh)
    }
  }, [])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <Access accessible={!!access.add || true}>
          <div className="toolbar">
            <Space>
              <Button type='primary' onClick={() => openEditPage('添加员工', 'edit')}>添加员工</Button>
            </Space>
          </div>
        </Access>
        <div className="form-area">
          <Form name='searchEmployeeForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='员工姓名' name='username'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='状态' name='status'>
                  <Select placeholder='请选择' options={enum2options(EmployeeStatus)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={employeeList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<Employee>
          rowKey='id'
          loading={employeeList.loading}
          dataSource={employeeList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: employeeList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
    </div>
  );
};

export default EmployeePage;
